package com.cqsw.bbs.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: ZackYoung
 * @time: 2020/6/14
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("登录过滤器启动成功");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        Object user = req.getSession().getAttribute("userList");
        String url = req.getRequestURI();
        url = url.replace("bbs/","");
        String loginPage = req.getContextPath() + "/login"+"?url="+url;
        if (user == null) {
            resp.sendRedirect(loginPage);
            return;
        }
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
        System.out.println("登录过滤器销毁成功");
    }
}
